var tagArr = [],
    lis = document.querySelectorAll("li"),
    tagList = document.querySelector(".tag-list");

function updateView() {

    for (var i = 0, leni = lis.length; i < leni; i++) {
        var li = lis[i],
            tagList = lis[i].classList,
            display = true;

        for (var j = 0, lenj = tagArr.length; j < lenj; j++) {
            if ([].indexOf.call(tagList, tagArr[j]) === -1) {
                display = false;
                break;
            }
        }

        if (display === false) {
            li.style.display = "none";
        } else {
            li.style.display = "block";
        }
    }

}

function addEventForTagList() {

    var tags = document.querySelectorAll(".tag-list > span");

    for (var i = 0, leni = tags.length; i < leni; i++) {
        tags[i].addEventListener("click", function (event) {
            var index = tagArr.indexOf(event.target.value);
            tagArr.splice(index, 1);
            event.target.parentElement.remove(event.target);
            updateView();
        });
    }
}

function init() {


    for (var i = 0, leni = lis.length; i < leni; i++) {

        var tags = lis[i].querySelectorAll(".tags span");

        for (var j = 0, lenj = tags.length; j < lenj; j++) {

            tags[j].addEventListener("click", function (event) {

                if (tagArr.indexOf(event.target.textContent) === -1) {
                    tagList.innerHTML += '<span>' + event.target.textContent + '<span class="delete">x</span></span>';
                    tagArr.push(event.target.textContent);
                    addEventForTagList();
                    updateView();
                }
                event.stopPropagation();
            });
        }

    }
}

window.onload = function() {

    init();

};